package com.zuqiuzhandui.liveing.view.login;

import android.content.Context;

import com.code19.library.GsonUtil;
import com.code19.library.L;
import com.zuqiuzhandui.liveing.common.CheckParameter;
import com.zuqiuzhandui.liveing.common.UserInfomationManage;
import com.zuqiuzhandui.liveing.model.resultModel.LoginRs;
import com.zuqiuzhandui.liveing.net.HttpMethods;
import com.zuqiuzhandui.liveing.net.ProgressSubscriber;
import com.zuqiuzhandui.liveing.net.SubscriberOnNextListener;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by yq on 2016-10-08.
 */

public class LoginPresenter implements LoginContract.Presenter {
    LoginContract.View view;

    public LoginPresenter(LoginContract.View view) {
        this.view = view;
        this.view.setPresenter(this);
    }

    @Override
    public void requestGetCode(String mobile) {
        String errorStr = CheckParameter.getInstance().checkPhone(mobile);
        if (errorStr != null) {
            view.showTip(errorStr);
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mobile);
        HttpMethods.getInstance().postSendCode(new ProgressSubscriber<Integer>(new SubscriberOnNextListener() {
            @Override
            public void onNext(Object o) {
                view.showSuccessGetCode();
            }

        }, (Context) view), map);
//        HttpMethods.getInstance().postSendCode(new Subscriber<HttpResult<Integer>>() {
//            @Override
//            public void onCompleted() {
//
//            }
//
//            @Override
//            public void onError(Throwable e) {
//
//            }
//
//            @Override
//            public void onNext(HttpResult<Integer> integerHttpResult) {
//                view.showSuccessGetCode();
//            }
//        },map);
    }

    @Override
    public void requestLogin(String mobile, String code) {
        String errorStr = CheckParameter.getInstance().checkLogin(mobile, code);
        if (errorStr != null) {
            view.showTip(errorStr);
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("mobile", mobile);
        map.put("captcha", code);

        HttpMethods.getInstance().postLogin(new ProgressSubscriber<LoginRs>(new SubscriberOnNextListener<LoginRs>() {
            @Override
            public void onNext(LoginRs o) {
                if (!view.isActive())
                    return;
                L.d(GsonUtil.objectToJson(o));
                UserInfomationManage.savaUser(o);
                view.showSuccessLogin();
            }
        }, ((LoginActivity) view)), map);
    }
}
